﻿using BaseAuthRole.Domain.Input;
using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.DTO.Knowledge;
using BaseAuthRole.DTO.Org;
using BaseAuthRole.DTO.Role;
using BaseAuthRole.IService;
using BaseAuthRole.Web.Filters;
using Lutos.Dictionary.SDK.Core;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RS.BaseModel.Common;
using RS.Environment;
using RS.Tool.Init;
using System.Collections.Generic;

namespace BaseAuthRole.Web.Controllers
{
    [Route("[controller]/[action]")]
    [PageAuthCheckFilter]
    [RoleActionCheckFilter]
    public class KnowledgeAuthManagerController : Controller
    {
        private readonly string DictionaryGatewayUrl = ConfigurationHelper.GetAppSettings("DictionaryGatewayUrl"); //字典地址
        private readonly string AppId = ConfigurationHelper.GetAppSettings("AppId");
        private readonly string Secret = ConfigurationHelper.GetAppSettings("Secret");

        private IUserService _userService;
        public KnowledgeAuthManagerController(IUserService userService)
        {
            this._userService = userService;
        }

        #region 视图
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 编辑知识类别权限
        /// </summary>
        /// <returns></returns>
        public ActionResult EditKnowledgeAuth(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                var knowledgeAuth = _userService.GetKnowledgeAuth(id);

                ViewData["knowledgeAuth"] = knowledgeAuth;

            }

            return View();
        }

        /// <summary>
        /// 知识类别权限详情
        /// </summary>
        /// <returns></returns>
        public ActionResult KnowledgeAuthDetail()
        {
            return View();
        }

        #endregion

        #region 请求
        [HttpGet]
        public string GetKnowledgeAuth(int pagenum, int pagesize, string para)
        {

            var result = new CommonResult();

            if (pagesize < 0)
            {

                pagesize = 1;
            }
            if (pagesize > 200)
            {
                pagesize = 200;

            }
            if (pagenum <= 0)
            {

                pagenum = 1;
            }

            long count = 0;

            var condition = "";

            Dictionary<string, object> obj = new Dictionary<string, object>();

            var info = this._userService.GetKnowledgeAuths(pagenum, pagesize, condition, " \"CreateTime\" desc", out count, obj);

            var total_num = Math.Ceiling(count / (decimal)pagesize);


            result.IsError = false;
            result.Result = new
            {

                content = info,
                total_num = total_num

            };
            return JsonConvert.SerializeObject(result);
        }

        [HttpPost]
        public string EditKnowledgeAuthDo([FromForm] EditKnowledgeAuthDoInput editKnowledgeAuthDoInput)
        {
            var result = new CommonResult();

            var relationActions = string.IsNullOrEmpty(editKnowledgeAuthDoInput.Data) ? new List<string>() : editKnowledgeAuthDoInput.Data.Split(',').ToList();

            if (string.IsNullOrEmpty(editKnowledgeAuthDoInput.DocumentCategory) || string.IsNullOrEmpty(editKnowledgeAuthDoInput.DocumentChildCategory))
            {
                result.Message = "类别,子类别不允许为空";
                return JsonConvert.SerializeObject(result);
            }

            if (!string.IsNullOrEmpty(editKnowledgeAuthDoInput.Id))
            {

                var knowledgeAuth = this._userService.GetKnowledgeAuth(editKnowledgeAuthDoInput.Id);

                if (knowledgeAuth == null)
                {
                    result.Message = "知识类别权限不存在";
                    return JsonConvert.SerializeObject(result);
                }

                var check = this._userService.CheckKnowledgeAuth(knowledgeAuth, knowledgeAuth.Id);
                if (check == 1)
                {
                    result.Message = "类别,子类别已存在";
                    return JsonConvert.SerializeObject(result);
                }

                knowledgeAuth.DocumentCategory = editKnowledgeAuthDoInput.DocumentCategory;
                knowledgeAuth.DocumentChildCategory = editKnowledgeAuthDoInput.DocumentChildCategory;
                knowledgeAuth.Description = editKnowledgeAuthDoInput.Description;

                var r = this._userService.UpdateKnowledgeAuth(knowledgeAuth, relationActions);

                if (r > 0)
                {

                    result.IsError = false;
                }

            }
            else
            {
                var check = this._userService.CheckKnowledgeAuth(new KnowledgeAuth 
                {
                    DocumentCategory = editKnowledgeAuthDoInput.DocumentCategory,
                    DocumentChildCategory = editKnowledgeAuthDoInput.DocumentChildCategory,
                });
                if (check == 1)
                {
                    result.Message = "类别,子类别已存在";
                    return JsonConvert.SerializeObject(result);
                }

                var knowledgeAuth = new KnowledgeAuth
                {
                    DocumentCategory = editKnowledgeAuthDoInput.DocumentCategory,
                    DocumentChildCategory = editKnowledgeAuthDoInput.DocumentChildCategory,
                    Description = editKnowledgeAuthDoInput.Description
                };
                var r = this._userService.CreateKnowledgeAuth(knowledgeAuth, relationActions);

                if (r > 0)
                {

                    result.IsError = false;
                }
            }
            return JsonConvert.SerializeObject(result);
        }

        [HttpGet]
        public string GetKnowledgeDictionary()
        {
            var result = new CommonResult();

            var appAccessToken = _userService.GetAppAccessTokenModel(AppId, Secret);
            LtDictionaryClient dictionaryClient = new LtDictionaryClient(DictionaryGatewayUrl);
            var dictionary = dictionaryClient.GetLtDictionaryDetailListByThirdPart(new Lutos.Dictionary.Domain.Integrate.Input.LtDictionaryDetailListGetThirdPartInputInfo
            {
                AppAccessToken = appAccessToken.Result.AppAccessToken,
                AppId = AppId,
                Id = "0",
                LtDictionaryCodes = new List<string>() { "SparePartTask_DocumentCategory" }
            }).Result.First();

            result.IsError = false;
            result.Result = dictionary;
            return JsonConvert.SerializeObject(result);
        }

        [HttpGet]
        public string GetKnowledgeAuthInfo(string id)
        {
            var result = new CommonResult();

            var objects = new List<string>();

            if (!string.IsNullOrEmpty(id))
            {
                objects = this._userService.GetKnowledgeAuthRelation(id);
            }

            var orgList = this._userService.GetOrgList().Result;

            var orgTreeOutPuts = new List<ActionTree>();

            BuildOrgTree(orgList, "0", objects, orgTreeOutPuts);

            result.IsError = false;

            result.Result = new { data = orgTreeOutPuts };

            return JsonConvert.SerializeObject(result);

        }

        /// <summary>
        /// 构造组织树结构
        /// </summary>
        /// <param name="infos">组织信息列表</param>
        /// <param name="parentId">父节点Id</param>
        /// <param name="objects">被选中节点</param>
        /// <param name="orgTreeOutPuts">组织树输出对象</param>
        /// <returns></returns>
        [NonAction]
        public static void BuildOrgTree(List<Organization> infos, string? parentId, List<string> objects, List<ActionTree> orgTreeOutPuts)
        {
            var orgs = infos.Where(p => p.ParentId == parentId).ToList();
            foreach (var org in orgs)
            {
                orgTreeOutPuts.Add(new ActionTree
                {
                    id = org.Id,
                    parent = org.ParentId == "0"? "#" : org.ParentId,
                    text = org.OrgName,
                    state = new ActionTreeState
                    {
                        selected = objects.Any(m => m == org.Id)
                    }
                });

                BuildOrgTree(infos, org.Id, objects, orgTreeOutPuts);
            }
        }
        #endregion
    }
}
